#!/usr/bin/python
import xmpp
import readline
import sys
import logging
from optparse import OptionParser

from jablit.commands import CommandAnalyzer
from jablit.listener import Listen
from jablit.client import Client
from jablit.utils import load_or_create_conf, bind_signals

def options():
    parser = OptionParser()
    parser.add_option("-l", "--log", dest="logfilename",
                      help="write status messages to FILE", metavar="FILE")
    parser.add_option("-v", "--verbose",
                      action="store_true", dest="verbose", default=False,
                      help="Print status messages to stdout")

    (options, args) = parser.parse_args()

    loggingconf = {'level': logging.CRITICAL}
    if options.verbose:
        loggingconf['level'] = logging.INFO
        loggingconf['format'] = '%(asctime)s %(levelname)s %(message)s'
    if options.logfilename:
        loggingconf['filename'] = options.logfilename
        loggingconf['filemode'] = 'w'
    logging.basicConfig(**loggingconf)

def main():
    options()
    conf = load_or_create_conf()
    bind_signals()
    jid = xmpp.protocol.JID(conf[0].jid)
    cl = xmpp.Client(jid.getDomain(), debug=[])
    client = Client(cl, jid, conf[0].password, (conf[0].server, conf[0].port))

    online = 1
    listener = Listen(online, cl, client)

    readline.parse_and_bind("tab: complete")
    readline.parse_and_bind('"\C-r": reverse-search-history')

    cmd = CommandAnalyzer(cl, client)


    try:
        try:
            while online:
                instr = raw_input(conf[0].prompt)
                cmd.run_once(instr)
        except Exception, e:
            import traceback
            e = "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))
            print e
    finally:
        print "quitting..."
        listener.online = 0
        cl.disconnect()
        sys.exit(0)

if __name__ == '__main__':
    main()
